from flask import Blueprint, render_template, request
import exts
from blueprints.forms import QuestionForm, AnswerForm
from models import Question, Answer
from flask import redirect, url_for,g
from zhuangshi import login_required

bp=Blueprint('qa', __name__, url_prefix='/')

@bp.route('/')
def index():
    questions = Question.query.all()
    return render_template('index.html',questions=questions)

@bp.route('/qa/public',methods=['GET','POST'])
@login_required
def public_question():
    form = QuestionForm(request.form)
    if request.method == 'GET':
        return render_template('public_question.html',form=form)
    elif request.method == 'POST':
        if form.validate():
            title=form.title.data
            content=form.content.data
            exts.db.session.add(Question(title=title,content=content,qusetion_setter_id=g.user.id))
            exts.db.session.commit()
            return redirect("/")
        else:
            return render_template('public_question.html',form=form)

@bp.route('/qa/detail/<qa_id>')
def qa_detail(qa_id):
    question = Question.query.get(qa_id)
    return render_template('detail.html',question=question)

@bp.route('/public_answer',methods=['POST'])
@login_required
def public_answer():
    form=AnswerForm(request.form)
    if form.validate():
        content=form.content.data
        question_id=form.question_id.data
        exts.db.session.add(Answer(question_id=question_id, content=content,answer_setter_id=g.user.id))
        exts.db.session.commit()
        return redirect(url_for('qa.qa_detail',qa_id=question_id))
    else:
        print(form.errors)
        return redirect(url_for('qa.qa_detail',qa_id=request.form.get('question_id')))

@bp.route('/search')
def search():
    q=request.args.get('q')
    questions = Question.query.filter(Question.title.contains(q)).all()
    return render_template('index.html',questions=questions)



